<template>
  <u-upload
    :fileList="fileListMap"
    @afterRead="afterRead"
    @delete="deletePic"
    name="1"
    :multiple="multiple"
    :maxCount="multiple ? maxCount : 1"
  ></u-upload>
</template>

<script>
import { uploadFile } from "@/services/api";

export default {
  props: {
    maxCount: {
      type: Number,
      default: 9,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    fileUrl: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      fileListMap: [],
    };
  },
  watch: {
    fileUrl: {
      immediate: true,
      handler(val) {
        if (val) {
          this.fileListMap = [
            {
              url: val,
              status: "success",
              message: "",
            },
          ];
        } else {
          this.fileListMap = [];
        }
      },
    },
  },
  methods: {
    deletePic(event) {
      this.fileListMap.splice(event.index, 1);
      this.$emit("update:fileUrl", this.fileListMap[0]?.url);
    },
    async afterRead(event) {
      let lists = [].concat(event.file);
      let fileListLen = this.fileListMap.length;

      lists.forEach((item) => {
        this.fileListMap.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });

      for (let i = 0; i < lists.length; i++) {
        try {
          console.log("上传的数据是", lists[i]);
          const { data, error } = await uploadFile({
            name: "file",
            filePath: lists[i].url,
            header: {
              "Content-Type": "multipart/form-data",
            },
          });
          if (error) throw error;
          const { url } = data;
          let item = this.fileListMap[fileListLen];

          this.fileListMap.splice(fileListLen, 1, {
            ...item,
            status: "success",
            message: "",
            url,
          });
          fileListLen++;
        } catch (e) {
          this.fileListMap.pop();
        }
      }

      this.$emit("update:fileUrl", this.fileListMap[0]?.url);
    },
  },
};
</script>

<style lang="scss" scoped></style>
